package com.invoice.analysis.ofd.service;


import com.invoice.analysis.entity.InvoiceEntity;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author 郑恩远
 * @version 1.0
 * @date 2024/11/7 11:52:26
 */
public class InvoiceService {

  public final Set<String> code;
  public final String name;
  public BiConsumer<InvoiceEntity, String> consumer;
  public BiConsumer<InvoiceEntity, BigDecimal> consumerBigDecimal;
  public InvoiceService(Set<String> code, String name, BiConsumer<InvoiceEntity, String> consumer) {
    this.code = code;
    this.name = name;
    this.consumer = consumer;
  }

  public InvoiceService(Set<String> code, String name) {
    this.code = code;
    this.name = name;
    this.consumer = null;
  }

  protected void setCommon(Node node, InvoiceEntity invoice, Map<String, String> contentMap) {
    String name = node.getNodeName();
    if (!this.code.contains(name)) {
      return;
    }
    String value = node.getTextContent();
    value = contentMap.get(value);
    value = value.replace(this.name, "");
    consumer.accept(invoice, value);
  }
  protected void setTrainCommon(String id, InvoiceEntity invoice, Map<String, String> contentMap) {
    String value = contentMap.get(id);
    value = StringUtils.isEmpty(value) ? value : value.replace(this.name, "");
    this.consumer.accept(invoice, value);
  }
  protected void setTrainAmount(String id, InvoiceEntity invoice, Map<String, String> contentMap) {
    String value = contentMap.get(id);
    BigDecimal amount = StringUtils.isEmpty(value) ? null : new BigDecimal(value.replace(this.name, ""));
    this.consumerBigDecimal.accept(invoice, amount);
  }

  protected void setAmount(Node node, InvoiceEntity invoice,
      Map<String, String> contentMap) {
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
      Node item = childNodes.item(i);
      String value = item.getTextContent();
      value = contentMap.get(value);
      if (StringUtils.isEmpty(value)) {
        continue;
      }
      try {
        BigDecimal taxExclusiveTotalAmount = new BigDecimal(value);
        this.consumerBigDecimal.accept(invoice, taxExclusiveTotalAmount);
        break;
      } catch (Exception ignored){}
    }

  }
}
